import axios from 'axios'
import { ElLoading } from 'element-plus'


const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8'
const contentTypeJson = 'application/json'
const responseTypeJson = 'json'
let loading = null

const instance = axios.create({
    withCredentials: true,
    baseURL: '/api',
    timeout: 10 * 1000
})

// 检查是否有其他地方覆盖 baseURL
if (!instance.baseURL) {
    console.error("baseURL is undefined after creating axios instance");
}

//请求前拦截器
instance.interceptors.request.use(
    (config) => {
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: '加载中......',
                background: 'rgba(0, 0, 0, 0.7)'
            })
        }
        return config
    },
    (error) => {
        if (error.config.showLoading && loading) {
            loading.close()
        }
        return Promise.reject('请求发送失败')
    }
)
//请求后拦截器
instance.interceptors.response.use(
    (response) => {
        const { showLoading, errorCallback, showError = true, responseType } = response.config
        if (showLoading && loading) {
            loading.close()
        }
        const responseData = response.data
        if (responseType == 'arraybuffer' || responseType == 'blob') {
            return responseData
        }
        //正常请求
        if (responseData.code == 200) {
            console.log('response is :', responseData)
            return responseData
        } else if (responseData.code == 401) {
            //登录超时
            setTimeout(() => {
                window.ipcRenderer.send('reLogin')
            }, 2000)
            return Promise.reject({ showError: true, msg: '登录超时' })
        } else {
            //其他错误
            if (errorCallback) {
                errorCallback(responseData)
                return
            }
            return Promise.reject({ showError: showError, msg: responseData.msg })
        }
    },
    (error) => {
        if (error.config.showLoading && loading) {
            loading.close()
        }
        return Promise.reject({ showError: true, msg: '网络异常' })
    }
)

/**
 * 发送请求的方法
 * @param config
 * @returns {Promise<axios.AxiosResponse<any>>}
 */

const request = (config) => {
    let {
        url,
        params,
        method = 'post', // 默认post请求
        data,
        showLoading = true,
        responseType = responseTypeJson,
        showError = true,
        contentType = contentTypeJson // 添加 contentType 参数
    } = config

    const token = localStorage.getItem('token')
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
        token: token
    }

    // 如果是 multipart/form-data，则不需要手动设置 Content-Type
    if (contentType !== contentTypeForm) {
        headers['Content-Type'] = contentType
    }

    const requestConfig = {
        headers: headers,
        showLoading: showLoading,
        errorCallback: config.errorCallback,
        showError: showError,
        responseType: responseType
    }
    if (method.toLowerCase() === 'post') {
        if (params) {
            url = url + '?'
            // 遍历参数对象
            for (const key in params) {
                const value = params[key]
                if (value === undefined || value === null || value === '') {
                    continue
                }
                url = url + key + '=' + value + '&'
            }
            url = url.substring(0, url.length - 1)
        }
        return instance.post(url, data, requestConfig).catch((error) => {
            if (error.showError) {
                alert(error.msg)
            }
            return undefined
        })
    } else if (method.toLowerCase() === 'get') {
        let formData = new FormData() // 创建form对象
        for (let key in params) {
            formData.append(key, params[key] === undefined ? '' : params[key])
        }
        requestConfig.params = params // GET请求使用params
        return instance.get(url, requestConfig).catch((error) => {
            if (error.showError) {
                alert(error.msg)
            }
            return null
        })
    } else {
        throw new Error('Unsupported request method')
    }
}

export default request
